<?php

namespace App\Services\MakeUserDeliveryAddress;

use App\Models\User;
use App\Models\Address;
use Illuminate\Http\Request;

class UpdateUserDeliveryAddress
{
	protected Address $address;

	protected Request $request;

	public function __construct(Address $address, Request $request)
	{
		$this->address = $address;
		$this->request = $request;
	}

	public function modify(): bool
	{
        $request = $this->request;

        /**
         * @var User $user
         */
        $user = $request->user();

		if ($request->is_default) {
			$user->addresses()->update(['is_default' => false]);
		}

        $address = $this->address;

		return $address->update([
            'id_code'           => $request->id_code ?? $address->id_code,
            'id_name'           => $request->id_name ?? $address->id_name,
            'contact_name'      => $request->contact_name ?? $address->contact_name,
            'contact_phone'     => $request->contact_phone ?? $address->contact_phone,
            'province'          => $request->province ?? $address->province,
            'city'              => $request->city ?? $address->city,
            'district'          => $request->district ?? $address->district,
            'province_code'          => $request->province_code ?? $address->province_code,
            'city_code'              => $request->city_code ?? $address->city_code,
            'district_code'          => $request->district_code ?? $address->district_code,
            'address'           => $request->address ?? $address->address,
            'is_default'        => $request->is_default ?? $address->is_default,
        ]);
	}

	public function update(): bool
	{
		return $this->modify();
	}
}
